package com.ruoyi.web.controller.payment.ceshi;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
 * Created by 小董 on 2021/2/2 17:07
 */
public class WxPayTool {
    /**
     * 回调地址
     */
    private static final String NOTIFY_URL = "http://localhost:8083/#/MaterialPay?orderId=133&totalPrice=100&availableId&productId=13";

    private static final String IP = "127.0.0.1";


    public static Map<String, String> wxPay(String money, String outTradeNo, String body,String attach,String uid ,String id) throws Exception {
        BigDecimal totalPrice = new BigDecimal(money);
        String totalFee = totalPrice.multiply(new BigDecimal(100)).toBigInteger().toString();
        OurWxConfig wxConfig = new OurWxConfig();
        WXPay wxPay = new WXPay(wxConfig);
        Map<String, String> param = new HashMap<>();
        param.put("appid", wxConfig.getAppID());
        param.put("mch_id",wxConfig.getMchID());

        // 支付场景 APP 微信app支付 JSAPI 公众号支付  NATIVE 扫码支付
        param.put("trade_type","APP");

        // 回调地址
        param.put("notify_url", NOTIFY_URL);

        // 终端ip
        param.put("spbill_create_ip", IP);

        // 订单总金额
        param.put("total_fee",totalFee);

        // 默认人民币
        param.put("fee_type","CNY");

        // 交易订单号
        param.put("out_trade_no",outTradeNo);

        // 内容
        param.put("body",body);

        // 生成随机字符串
        param.put("nonce_str", WXPayUtil.generateNonceStr());

        //一次签名
        WxMD5Util md5Util = new WxMD5Util();
//        String oneSign = md5Util.getSign(param);
        String oneSign = WXPayUtil.generateSignature(param,wxConfig.getKey());
        param.put("sign",oneSign);

        /**
         * wxPay.unifiedOrder 这个方法中调用微信统一下单接口
         */
        Map<String, String> respData = wxPay.unifiedOrder(param);

        System.out.println();
        System.out.println("返回结果------" + respData.toString());
        System.out.println();

        if (respData.get("return_code").equals("SUCCESS")){
            //返回给APP端的参数，APP端再调起支付接口
            Map<String, String> res = new HashMap<>();
            res.put("appid",wxConfig.getAppID());
            res.put("noncestr",respData.get("nonce_str"));
            res.put("partnerid",wxConfig.getMchID());
            res.put("timestamp",String.valueOf(System.currentTimeMillis()/1000));
            res.put("package","Sign=WXPay");
            res.put("prepayid",respData.get("prepay_id"));

            //签名
            String sign = WXPayUtil.generateSignature(res, wxConfig.getKey());
            res.put("sign", sign);

            System.out.println("新的验签-----------" + sign);

            return res;
        }
        System.out.println("----------报错" + respData.get("return_msg"));
        throw new Exception(respData.get("return_msg"));
    }

    public static String wxNotify(HttpServletRequest request) {
        System.out.println("微信支付回调");
        try {
            // 读取参数
            // 解析xml成map
            Map<String, String> map = WXPayUtil.xmlToMap(getParam(request));
            System.out.println("微信支付回调返回的信息：" + map);
//            check(map);//该处读者自行校验（验证订单号，付款金额等是否正确）
            String orderNo = map.get("out_trade_no");
            String resultCode = map.get("result_code");
            // 另起线程处理业务
            System.out.println();
            System.out.println("另起线程处理业务");
            System.out.println();
            if (resultCode.equals("SUCCESS")) {
                return setXml("SUCCESS", "OK");
            } else {
                return setXml("fail", "付款失败");
            }
        } catch (Exception e) {
            System.out.println("微信支付回调发生异常：" + e.getLocalizedMessage());
            return setXml("fail", "付款失败");
        }

    }

    private static String getParam(HttpServletRequest request) throws IOException {
        // 读取参数
        InputStream inputStream;
        StringBuilder sb = new StringBuilder();
        inputStream = request.getInputStream();
        String s;
        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        while ((s = in.readLine()) != null) {
            sb.append(s);
        }
        in.close();
        inputStream.close();
        return sb.toString();
    }

    /**
     * 通过xml发给微信消息
     * @param return_code
     * @param return_msg
     * @return
     */
    private static String setXml(String return_code, String return_msg) {
        SortedMap<String, String> parameters = new TreeMap<>();
        parameters.put("return_code", return_code);
        parameters.put("return_msg", return_msg);
        try {
            return WXPayUtil.mapToXml(parameters);
        } catch (Exception e) {
            System.out.println("返回微信消息时map转xml失败");
            return "<xml><return_code><![CDATA[" + return_code + "]]>" + "</return_code><return_msg><![CDATA[" + return_msg
                    + "]]></return_msg></xml>";
        }
    }
}
